package com.stephen.jsbridge.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.stephen.jsbridge.jsbridge.BridgeHandler;
import com.stephen.jsbridge.jsbridge.CallBackFunction;
import com.stephen.jsbridge.jsbridge.OnWebViewListener;
import com.stephen.jsbridge.xwalkbridge.XWalkWebChromeClient;
import com.stephen.jsbridge.xwalkbridge.XWalkWebView;
import com.stephen.jsbridge.xwalkbridge.XWalkWebViewClient;

/**
 * Created by Stephen on 2016/8/21.
 */
public class StephenCrossWalkTool {
    private Activity activity;
    private XWalkWebView bridgeWebView = null;
    private BridgeHandler bridgeHandler = null;

    public StephenCrossWalkTool(Activity activity) {
        this.activity = activity;
        bridgeWebView = new XWalkWebView(activity);
    }

    public void initJsBridgeWebView(boolean notSetClient,OnWebViewListener onWebViewListener){
        if(null != bridgeWebView)bridgeWebView.init(activity,notSetClient,onWebViewListener);
    }

    public void addHtmlCallNativeCommand(BridgeHandler bridgeHandler,String command){
        this.bridgeHandler = bridgeHandler;
        if(null != bridgeWebView && !TextUtils.isEmpty(command))bridgeWebView.registerHandler(command,bridgeHandler);
    }

    public void addHtmlCallNativeCommandAry(BridgeHandler bridgeHandler,String... commandAry){
        this.bridgeHandler = bridgeHandler;
        if(null != bridgeWebView && null != commandAry && commandAry.length > 0)for(String command : commandAry)if(!TextUtils.isEmpty(command))bridgeWebView.registerHandler(command,bridgeHandler);
    }

    public void execJsMethod(String jsMethodName){
        if(null != bridgeWebView)bridgeWebView.loadUrl("javascript:"+jsMethodName+"()");
    }

    public void loadUrl(String loadUrl){
        //loadUrl += ("?t="+System.currentTimeMillis());
        System.out.println("=============>加载链接:"+loadUrl);
        if(null != bridgeWebView)bridgeWebView.loadUrl(loadUrl);
    }

    public XWalkWebView getBridgeWebView() {
        return bridgeWebView;
    }

    public BridgeHandler getBridgeHandler() {
        return bridgeHandler;
    }

    public void nativeCallHtmlCommand(String handlerName, String data, CallBackFunction callBack){
        getBridgeWebView().callHandler(handlerName, data, callBack);
    }

    public XWalkWebViewClient getWebViewClient() {
        return null != bridgeWebView ? bridgeWebView.getWebViewClient() : null;
    }

    public XWalkWebChromeClient getWebChromeClient() {
        return null != bridgeWebView ? bridgeWebView.getWebChromeClient() : null;
    }

    public void setWebHtmlLoadMode(boolean isHardWare){
        if(null != bridgeWebView)bridgeWebView.setLayerType(isHardWare ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_SOFTWARE,null);
    }
}
